<template>
  <div class="addTroops-component">
    <!-- 新增-->
    <Cell class="w">
      <div class="title-w">
        <Icon @click="router.go(-1)" size="18" name="arrow-left" />
        <div class="title">
          <div>{{ route.query.id ? "编辑" : "新增" }}拜访报告</div>
        </div>
      </div>
    </Cell>

    <!-- 表单 -->
    <Form @submit="onSubmit" :scroll-to-error="true">
      <CellGroup class="pb" inset>
        <!-- 拜访时间 -->
        <Field v-model="form.visitTime" is-link required readonly name="picker" label="拜访日期" placeholder="请选择" @click="showPickerTime = true" :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerTime" position="bottom">
          <DatetimePicker @confirm="onConfirmTime" @cancel="showPickerTime = false" v-model="currentDate" type="date" title="选择年月日" />
        </Popup>

        <!-- 出差计划 -->
        <Field v-model="planValue" is-link readonly name="picker" label="出差计划" placeholder="请选择" @click="showPickerPlan = true" />
        <Popup v-model:show="showPickerPlan" position="bottom">
          <Picker :columns-field-names="planFieldName" :columns="columnsPlan" title="选择出差计划" @confirm="onConfirmPlan" @cancel="showPickerPlan = false"> </Picker>
        </Popup>

        <!--  客户 -->
        <Field
          v-model="customerName"
          is-link
          required
          readonly
          name="picker"
          label="客户"
          placeholder="注意：只能选CRM已有的客户"
          @click="showPickerCust = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerCust" :close-on-click-overlay="false" position="bottom">
          <Picker :columns-field-names="customFieldName" :columns="columnsCustomer" @confirm="onConfirmCustom" @cancel="cancelCustomer">
            <template #title>
              <Search style="width: 60%" v-model="customerName" @update:model-value="searchCustomerName" placeholder="请输入搜索关键词" />
            </template>
          </Picker>
        </Popup>

        <!--  客户联系人 多选 -->
        <Field v-model="form.contact" required is-link readonly name="picker" label="联系人" placeholder="请选择" @click="setContact" :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerContact" :style="{ height: '60%' }" position="bottom">
          <div style="display: flex; align-items: center">
            <Search style="width: 85%" v-model="contactName" @update:model-value="searchonContactName" placeholder="请输入联系人名字" />
            <Button size="small" @click="onConfirmContact()" type="primary">确认</Button>
          </div>
          <Cell v-if="columnsonContact?.length > 0" class="dept" v-for="(item, index) in columnsonContact" :key="index">
            <Checkbox v-model="item.checked">
              <div class="user">
                <div class="user-items">
                  <span class="name" v-if="item.name">{{ item?.name }} </span>
                </div>
              </div>
            </Checkbox>
          </Cell>
          <Empty v-else class="mt3" image-size="80" image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" :description="`${customerName ? '暂无项目数据' : '请先选择客户！'}`" />
        </Popup>

        <!--  项目  多选-->
        <Field v-model="form.visitProjects" is-link readonly name="picker" label="项目" placeholder="请选择" @click="setProject" />
        <Popup v-model:show="showPickerProject" :style="{ height: '60%' }" position="bottom">
          <div style="display: flex; align-items: center">
            <Search style="width: 85%" v-model="projectName" @update:model-value="searchProjectName" placeholder="请输入项目编号" />
            <Button size="small" @click="onConfirmProject()" type="primary">确认</Button>
          </div>
          <Cell v-if="columnsonProject?.length > 0" class="dept" v-for="(item, index) in columnsonProject" :key="index">
            <Checkbox v-model="item.checked">
              <div class="user">
                <div class="user-items">
                  <span class="name" v-if="item.name">{{ item?.name }} </span>
                  <span style="margin-left: 20px; color: #3249cf">【{{ item.projectName }}】</span>
                </div>
              </div>
            </Checkbox>
          </Cell>
          <Empty v-else class="mt3" image-size="80" image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" :description="`${customerName ? '暂无项目数据' : '请先选择客户！'}`" />
        </Popup>

        <!-- 拜访方式 -->
        <Field
          v-model="form.visitType"
          is-link
          required
          readonly
          name="picker"
          label="拜访方式"
          placeholder="点击选择拜访方式"
          @click="showPickerType = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerType" position="bottom">
          <Picker :columns="columns" @confirm="onConfirmType" @cancel="showPickerType = false" />
        </Popup>

        <!--  军品 -->
        <div>
          <Field v-model="form.推广品牌" name="推广品牌" required label="推广品牌" placeholder="请输入" :rules="[{ required: true, message: '请填推广品牌' }]" />
          <Field
            label-width="150px"
            @click="setOutuser"
            v-model="form.我司出席人员"
            name="我司出席人员"
            label="我司出席人员"
            required
            placeholder="请输入"
            :rules="[{ required: true, message: '请填写我司出席人员' }]" />
          <Popup v-model:show="showPicker" position="bottom">
            <Picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
          </Popup>
          <Field label-width="150px" label="原厂出席人员" v-model="form.原厂出席人员" placeholder="请输入" />
          <Field label-width="170px" label="客户与会人员及职位" v-model="form.客户与会人员及职位" required placeholder="请输入" :rules="[{ required: true, message: '请填写客户与会人员及职位' }]" />
          <Field label="目的及结果1" type="textarea" autosize required v-model="form.目的及结果1" placeholder="请输入" :rules="[{ required: true, message: '目的及结果1' }]" />
          <Field label="目的及结果2" type="textarea" autosize v-model="form.目的及结果2" placeholder="请输入" />
          <Field label="目的及结果3" type="textarea" autosize v-model="form.目的及结果3" placeholder="请输入" />
          <Cell>
            <span class="req new">新增认识人员数</span>
            <Stepper v-model="form.新增认识人员数" min="" integer :default-value="0" />
          </Cell>
          <Field
            label-width="150px"
            label="新增人名,职位,部门"
            v-model="form.新增人名职位部门"
            type="textarea"
            required
            autosize
            placeholder="请输入"
            :rules="[{ required: true, message: '新增人名,职位,部门' }]" />

          <Field type="textarea" autosize v-model="form.困难及问题" name="困难及问题" label="困难及问题" required placeholder="请输入" :rules="[{ required: true, message: '请填写困难及问题' }]" />
          <Field
            v-model="form.关注度等级"
            is-link
            required
            readonly
            name="picker"
            label="关注度等级"
            placeholder="点击选择关注度等级"
            @click="showPickerLeve = true"
            :rules="[{ required: true, message: '请选择' }]" />
          <Popup v-model:show="showPickerLeve" position="bottom">
            <Picker :columns="columnsLeve" @confirm="onConfirmLeve" @cancel="showPickerLeve = false" />
          </Popup>
          <Field v-model="form.cost" name="费用开销" label="费用开销" required placeholder="请输入" :rules="[{ required: true, message: '费用开销' }]" />
          <!--<span class="req">跟进计划1</span>-->
          <Field label="跟进计划1" type="textarea" autosize v-model="form.跟进计划1" required placeholder="请输入" :rules="[{ required: true, message: '请填写跟进计划1' }]" />
          <Field label="跟进计划2" type="textarea" autosize v-model="form.跟进计划2" placeholder="请输入" />
          <Field label="跟进计划3" type="textarea" autosize v-model="form.跟进计划3" placeholder="请输入" />
          <Field label="需要公司的支持" type="textarea" autosize v-model="form.需要公司的支持" placeholder="请输入需要公司支持" />
        </div>

        <!-- 图片上传 -->
        <Field name="uploader" label="图片上传">
          <template #input>
            <uploadImg @updateFileList="updateFileList" :fileList="form.imgs || []" />
          </template>
        </Field>

        <!-- 附件上传 -->
        <Field name="uploader" label="附件上传">
          <template #input>
            <uploadImg fileType=".pdf,.doc,.docx" @updateFileList="updateFile" :fileList="form.files || []" maxSize="1100000000" />
          </template>
        </Field>

        <Field v-model="form.remark" type="textarea" autosize name="备注" label="备注" placeholder="提醒注意阻容/检测/国产化／其它业务" />
        <!-- 头像 -->
        <div class="avter">
          <Cell>
            <div class="user-w">
              <span> 发送到人 </span>
              <div class="user" v-for="(item, index) in userList" :key="index">
                <Image radius="5" round class="imgs" width="0.9rem" height="0.9rem" :src="item.img" />
                <Icon v-if="item.isLock" color="#1989fa" class="lock" name="lock" />
                <Icon v-else @click="closeUser(index)" color="#1989fa" class="lock" name="close" />
                <div v-if="item.userName" class="f13">{{ item.userName }}</div>
              </div>
              <!-- 新增user弹窗 -->
              <Icon @click="addUser" class="i" size="30" name="plus" />
            </div>
          </Cell>
        </div>

        <!-- 转发 -->
        <div class="share"><span class="reqno">是否转发</span> <Checkbox @change="setShare" v-model="form.forward" shape="square"></Checkbox></div>
        <!-- 底部提交 -->
      </CellGroup>
      <div class="m16">
        <Button round size="small" type="primary" class="btn" native-type="submit" @click="set(1)"> 提交 </Button>
        <Button round size="small" type="warning" class="btn" native-type="submit" @click="set(0)"> 存草稿 </Button>
      </div>
    </Form>

    <!-- 人员弹窗 -->
    <VanDialog v-model:show="show" :closeOnClickOverlay="true" :showConfirmButton="false" title="深圳市斯贝达电子有限公司">
      <User :isType="isType" @back="back" @callback="setCheckUser"></User>
    </VanDialog>
  </div>
</template>
<script setup name="addTrade">
import { ref, reactive, onMounted } from "vue";
import uploadImg from "@/components/uploadImg.vue";
import { Cell, Button, Checkbox, Form, Field, Popup, Picker, CellGroup, Image, Icon, Stepper, DatetimePicker, Search, Toast, Dialog, Empty } from "vant";
import { useRouter, useRoute } from "vue-router";

import { Local } from "@/utils/storage";
import { setTime, userLockList } from "@/utils/index";

import User from "@/views/user/index.vue";

import { getCustomList, addVisitRecords, projectList, getVisitInfoById, updateVisitRecords, tripPlanList_Vistt, getContactsList, getProjectByContactIds } from "@/api/index";

const router = useRouter();
const route = useRoute();

const VanDialog = Dialog.Component;

const userList = ref([]);

const TYPE = route.query.type;

const form = reactive({
  visitTime: "",
  customerID: undefined,
  visitTemplate: "军品事业部",
  remark: "",
  userId: Local.get("userId"),
  userName: Local.get("userName"),
  sendTo: [],
  forward: 0, //是否可以转发 1 可以 0 不可以
  imgs: "",
  files: "",
  visitProjects: "",
  visitType: "",
  visitContent: "", // 这里对应的crm 的拜访记录的文本域
  visitContentJson: "", // 用户详情回显
  tripPlanId: 0, // 出差计划
  contact: "", // 客户联系人
});

// 初始化数据
const currentId = ref(0);
onMounted(async () => {
  if (userList.value?.length == 0) {
    userList.value = userLockList;
  }
  await _getCustList();

  // 编辑的时候
  if (route?.query.id) {
    currentId.value = route.query.id;
    await _getVisitInfoById(currentId.value);
  }
});

// 获取数据详情
const _getVisitInfoById = async (id) => {
  let { data } = await getVisitInfoById({ id });
  // 处理 visitContentJson 的数据
  data.visitContentJson = JSON.parse(data.visitContentJson);
  // 客户名字回显
  customerName.value = data.customerName;
  planValue.value = data.reason;
  form.contact = data.contactsName;
  if (data.imgs) {
    data.imgs = data.imgs.split(",");
    data.imgs = data.imgs?.map((v) => {
      return { url: v };
    });
  }
  if (data.files) {
    data.files = data.files.split(",");
    data.files = data.files?.map((v) => {
      return { url: v };
    });
  }
  // 去除空格
  for (let key in data.visitContentJson) {
    data.visitContentJson[key] = data.visitContentJson[key].replace(/"/g, "");
  }
  // 合并josn里面的字段
  data = { ...data, ...data.visitContentJson };
  // 重置模板
  data.visitContentJson = "";
  // 回显发送的人 过滤原本固定的成员
  const result = data.sendToJson.filter((obj1) => !userLockList.some((obj2) => obj2.userId === obj1.userId));
  userList.value = [...userLockList, ...result];

  Object.assign(form, data);
};

// 区别是草稿 还是 提交
const set = (num) => {
  console.log(num);
  form.state = num;
};

// 设置转发
const setShare = (e) => {
  //1 可以 0 不可以
  form.forward = e ? 1 : 0;
};

const back = () => {
  show.value = false;
};

// 关注度等级
const showPickerLeve = ref(false);
const columnsLeve = ["重要", "一般", "不重要", "关注"];
const onConfirmLeve = (value) => {
  form.关注度等级 = value;
  showPickerLeve.value = false;
};

// 确认选择时间
const showPickerTime = ref(false);
const currentDate = ref(new Date());
const onConfirmTime = (value) => {
  form.visitTime = setTime(value);
  showPickerTime.value = false;
};

// 获取出差记录列表
const planFieldName = {
  text: "reason",
};
const columnsPlan = ref([]);
const getTripPlanList = async () => {
  let res = await tripPlanList_Vistt({
    userid: Local.get("userId"),
  });
  columnsPlan.value = res.data;
  console.log("getTripPlanList", res);
};

getTripPlanList();

// 确认选择出差记录
const showPickerPlan = ref(false);
const planValue = ref("");

const onConfirmPlan = (e) => {
  // 清空客户，联系人，项目
  customerName.value = "";
  form.customerID = 0;
  form.contact = "";
  form.contactsId = "";
  form.visitProjects = "";
  form.tripPlanId = e.id; // 出差计划的id
  // 筛选对应的客户和联系人
  _getCustList(null, e.id);
  planValue.value = e.reason;
  showPickerPlan.value = false;
};

// 客户联系人
const showPickerContact = ref(false);
const contactName = ref("");
const columnsonContact = ref([]);
const onConfirmContact = () => {
  // 重置项目信息
  form.visitProjects = "";
  let arr = [];
  let ids = [];
  columnsonContact.value.map((v) => {
    if (v.checked) {
      arr.push(v.name);
      ids.push(v.id);
    }
  });
  form.contact = arr.toString();
  form.contactsId = ids.toString();
  _getProjectList(form.contactsId, "");
  showPickerContact.value = false;
};

// 获取联系人列表
const _getContactList = async (name, id) => {
  let res = await getContactsList({ name, id });
  columnsonContact.value = res.data;
};

// 点击 选择联系人
const setContact = () => {
  if (!customerName.value) {
    return Toast("请先选择客户");
  }
  showPickerContact.value = true;
};

// 根据名字查询客户联系人e
const searchonContactName = (e) => {
  _getContactList(e, form.customerID);
};

// 获取客户列表数据
const customFieldName = {
  text: "name",
};
const columnsCustomer = ref([]);
const _getCustList = async (name, id = 0) => {
  let { data } = await getCustomList({ name, id, userid: Local.get("userId") });
  columnsCustomer.value = data;
  console.log("获取客户列表数据", data);
};

// 确认选择客户
const showPickerCust = ref(false);
const onConfirmCustom = (e) => {
  // 重置项目和联系人
  form.contact = "";
  form.contactsId = "";
  form.visitProjects = "";
  customerName.value = e.name;
  form.customerID = Number(e.id);
  _getContactList("", form.customerID);
  showPickerCust.value = false;
};

// 取消客户
const cancelCustomer = () => {
  showPickerCust.value = false;
  customerName.value = "";
};

// 查询客户
const customerName = ref("");
const searchCustomerName = (e) => {
  _getCustList(e, form.tripPlanId || undefined);
};

//获取项目列表
const columnsonProject = ref([]);
const _getProjectList = async (id, name) => {
  let { data } = await getProjectByContactIds({ id, name });
  columnsonProject.value = data;
};

// 确认选择项目
const showPickerProject = ref(false);
const onConfirmProject = () => {
  let arr = [];
  columnsonProject.value.map((v) => {
    if (v.checked) {
      arr.push(v.name);
    }
  });
  form.visitProjects = arr.toString();
  showPickerProject.value = false;
};

// 查询项目
const projectName = ref("");
const searchProjectName = (e) => {
  _getProjectList(form.contactsId, e);
};

// 点击 选择项目
const setProject = () => {
  if (!form.contact) {
    return Toast("请先选择联系人");
  }
  showPickerProject.value = true;
};

// 删除选择的用户
const closeUser = (index) => {
  userList.value.splice(index, 1);
};

// 设置我司出席人员
const isType = ref(null);
const show = ref(false);
const setOutuser = () => {
  isType.value = 1;
  show.value = true;
};

// 跳转到关联选择用户
const addUser = () => {
  show.value = true;
  isType.value = 2;
};

// 设置人员
const setCheckUser = (e) => {
  if (isType.value == 1) {
    form.我司出席人员 = e
      .map((v) => {
        return v.userName;
      })
      .toString();
  } else {
    // 过滤
    const result = e.filter((obj1) => !userList.value.some((obj2) => obj2.userId === obj1.userId));
    userList.value = [...userList.value, ...result];
  }
  show.value = false;
};

// 拜访方式
const showPickerType = ref(false);
const columns = ["当面拜访", "电话拜访", "聊天软件拜访", "其他"];
const onConfirmType = (val) => {
  form.visitType = val;
  showPickerType.value = false;
};

// 上传图片
const updateFileList = (row) => {
  console.log("上传图片", row);
  form.imgs = row;
};

// 上传附件
const updateFile = (row) => {
  form.files = row;
};

// 提交
const onSubmit = async (e) => {
  // 把userid变成josn字符串
  form.sendTo = userList.value
    .map((v) => {
      return v.userId;
    })
    .toString();

  //数据处理图片
  if (Array.isArray(form.imgs)) {
    form.imgs = form.imgs
      ?.map((v) => {
        return v.url;
      })
      .toString();
  }

  //数据处理附件
  if (Array.isArray(form.files)) {
    form.files = form.files
      .map((v) => {
        return v.url;
      })
      .toString();
  }
  // crm 军品文本域模板
  form.visitContent = `<p style=\"text-align: left;\"><strong>推广品牌</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.推广品牌
  }</span></p>
  <p style=\"text-align: left;\"><strong>*我司出席人员</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.我司出席人员
  }</span></p>
  <p style=\"text-align: left;\"><strong>原厂出席人员</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.原厂出席人员 || "无"
  }</span></p>
  <p style=\"text-align: left;\"><strong>*拜访方式</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.visitType
  }</span></p>
  <p style=\"text-align: left;\"><strong>*客户与会人员及职位</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.客户与会人员及职位
  }</span></p>
  <p style=\"text-align: left;\"><strong>*目的及结果1:</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.目的及结果1 || "无"
  }</span></p>
  <p style=\"text-align: left;\"><strong>目的及结果2:</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.目的及结果2 || "无"
  }</span></p>
  <p style=\"text-align: left;\"><strong>目的及结果3:</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.目的及结果3 || "无"
  }</span></p>
  <p style=\"text-align: left;\"><strong>*新增认识人员数</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.新增认识人员数
  }</span></p>
  <p style=\"text-align: left;\"><strong>*新增人名,职位,部门</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.新增人名职位部门
  }</span></p>
  <p style=\"text-align: left;\"><strong>*困难及问题</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.困难及问题
  }</span></p>
  <p style=\"text-align: left;\"><strong>*关注度等级</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.关注度等级
  }</span></p>
  <p style=\"text-align: left;\"><strong>*跟进计划1:</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.跟进计划1
  }</span></p>
  <p style=\"text-align: left;\"><strong>跟进计划2:</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.跟进计划2 || "无"
  }</span></p>
  <p style=\"text-align: left;\"><strong>跟进计划3:</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.跟进计划3 || "无"
  }</span></p>
  <p style=\"text-align: left;\"><strong>需要公司的支持</strong></p><p style=\"text-align: left;\"><span style=\"color: rgb(64, 64, 64);\"> </span><span style=\"color: rgb(64, 64, 64); font-family: 宋体;\">${
    form.需要公司的支持 || "无"
  }</span></p><p> </p>`;

  console.log("form", form);
  // 循环对象 找出对象key 为字符串的字段 放在visitContentJson里面
  let visitContentJson = {};
  for (let key in form) {
    if (/[\u4e00-\u9fa5]/.test(key)) {
      visitContentJson[key] = JSON.stringify(form[key]);
    }
  }
  form.visitContentJson = JSON.stringify(visitContentJson);
  // 删除 这些自己定义的key
  for (let key in form) {
    if (/[\u4e00-\u9fa5]/.test(key)) {
      console.log(key);
      await delete form[key];
    }
  }

  let res;
  if (route.query.id) {
    delete form.新增认识人员数;
    delete form.sendToJson;
    delete form.customerName;
    delete form.userImg;
    delete form.createTime;
    form.id = Number(route.query.id);
    res = await updateVisitRecords(form);
  } else {
    res = await addVisitRecords(form);
  }
  if (res.code == 200) {
    router.go(-1);
    Toast(`${route.query.id ? "编辑" : "新增"}成功`);
  }
};
</script>
<style>
@import "../../assets/styles/index.scss";
</style>
<style lang="scss" scoped>
@import "./index.scss";
</style>
